﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLL;
using SMSModels;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SMSUI.GoodsManager
{
    public partial class FrmInStoreManager : Form
    {
        private BLL.GoodsManager.InStoreManager inStoreManager = new BLL.GoodsManager.InStoreManager();
        private BLL.BaseIndo.GoodsFilesManager goodsFilesManager = new BLL.BaseIndo.GoodsFilesManager();
        private BLL.BaseIndo.StoreManager storeManager = new BLL.BaseIndo.StoreManager();
        private BLL.BaseIndo.SupplierManager supplierManager = new BLL.BaseIndo.SupplierManager();
        DataSet gfds;
        DataSet storeds;
        DataSet supplierds;
        List<string> printList = new List<string>();

        public FrmInStoreManager()
        {
            InitializeComponent();
            if (Program.currentUser.Power != 0) //非管理员禁用 修改、删除
            {
                btnRevise.Enabled = false;
                btnDelete.Enabled = false;
            }
            gfds = goodsFilesManager.GetDataSet();
            storeds = storeManager.GetDataSet();
            supplierds = supplierManager.GetDataSet();
        }
        //窗口加载绑定数据
        private void FrmInStoreManager_Load(object sender, EventArgs e)
        {
            //List<Goods>list= goodsFilesManager.GetGoodsInfo();
            //绑定入库信息数据到dgv
            DataSet myds = inStoreManager.GetDataSetFromInStoreTable();
            dgvInStoreInfo.DataSource = myds.Tables["inStoreInfo"];

            //绑定货物编号组合框数据
            cmbGoodsNum.DataSource = gfds.Tables[0];
            cmbGoodsNum.DisplayMember = "货物编号";
            cmbGoodsNum.SelectedIndex = -1;
            //绑定货物名称组合框数据
            cmbGoodsName.DataSource = gfds.Tables[0];
            cmbGoodsName.DisplayMember = "货物名称";
            cmbGoodsName.SelectedIndex = -1;
            //绑定仓库名称组合框数据
            cmbStoreName.DataSource = storeds.Tables[0];
            cmbStoreName.DisplayMember = "仓库名称";
            cmbStoreName.ValueMember = "仓库ID";
            cmbStoreName.SelectedIndex = -1;
            //绑定供货商名称组合框数据
            cmbSupplierName.DataSource = supplierds.Tables[0];
            cmbSupplierName.DisplayMember = "供货商名称";
            cmbSupplierName.ValueMember = "供货商ID";
            cmbSupplierName.SelectedIndex = -1;
            //绑定规格组合框数据
            cmbSpe.DataSource = gfds.Tables[0];
            cmbSpe.DisplayMember = "规格";
            cmbSpe.SelectedIndex = -1;
            //绑定计量单位组合框数据
            cmbUnits.DataSource = gfds.Tables[0];
            cmbUnits.DisplayMember = "计量单位";
            cmbUnits.SelectedIndex = -1;

            DeleDOC();
        }
        //退出
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //列表单击选择
        private void dgvInStoreInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            cmbGoodsNum.Text= dgvInStoreInfo[1, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //货物编号
            cmbGoodsName.Text = dgvInStoreInfo[2,dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //货物名称

            cmbStoreName.Text = dgvInStoreInfo[4, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //仓库名称
            //Console.WriteLine(cmbStoreName.SelectedValue);

            cmbSupplierName.Text = dgvInStoreInfo[6, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //供货商名称
            //Console.WriteLine(cmbSupplierName.SelectedValue);

            cmbSpe.Text = dgvInStoreInfo[7, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //规格
            cmbUnits.Text = dgvInStoreInfo[8, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //计量单位
            cmbInStoreMonovalent.Text = dgvInStoreInfo[9, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //单价
            txtInStoreQuantity.Text = dgvInStoreInfo[10, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //入库数量
            txtTotal.Text = dgvInStoreInfo[11, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //总金额
            txtHandler.Text = dgvInStoreInfo[13, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //经手人
            txtRemarks.Text = dgvInStoreInfo[14, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString();  //备注

            
        }


        //入库
        private void btnInStorage_Click(object sender, EventArgs e)
        {
            if (cmbGoodsNum.Text.Length == 0 || cmbGoodsName.Text.Length == 0 || cmbStoreName.Text.Length == 0 || cmbSupplierName.Text.Length == 0 || cmbSpe.Text.Length == 0 || cmbUnits.Text.Length == 0 || cmbInStoreMonovalent.Text.Length == 0 || txtInStoreQuantity.Text.Trim().Length == 0 || txtTotal.Text.Trim().Length == 0 || txtHandler.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写完整！");
            }
            else
            {
                InStore inStore = new InStore
                {
                    InStoreID = "rk" + DateTime.Now.ToString("yyyyMMddHHmmss"), //入库编号
                    GoodsID= cmbGoodsNum.Text,  //货物编号
                    StoreID = Convert.ToInt32(cmbStoreName.SelectedValue),  //仓库ID
                    SupplierID = Convert.ToInt32(cmbSupplierName.SelectedValue),  //供货商ID
                    InStoreMonovalent = Convert.ToDouble(cmbInStoreMonovalent.Text.Trim()),  //入库单价
                    InStoreQuantity = Convert.ToInt32(txtInStoreQuantity.Text.Trim()),  //入库数量
                    InStoreTotal = Convert.ToDouble(txtTotal.Text.Trim()),  //总金额
                    InStoreTime = DateTime.Now.ToString("yyyy年MM月dd日HH时mm分"),  //入库时间
                    Handler = txtHandler.Text.Trim(),  //经手人
                    Remarks = txtRemarks.Text.Trim()  //备注
                };

                if (inStoreManager.IsExists(inStore))   //库存表中货物存在
                {
                    if (inStoreManager.InStore(inStore) > 0 && inStoreManager.UpdateStorageOnInStore(inStore) > 0)//插入入库表记录，更新库存表库存数量
                    {
                        MessageBox.Show("入库成功！");
                        FrmInStoreManager_Load(sender, e);
                    }
                    else
                    {
                        MessageBox.Show("入库失败！请检查！");
                    }
                }
                else     //库存表中货物不存在
                {
                    if (inStoreManager.InStore(inStore) > 0 && inStoreManager.InsertStorageTable(inStore) > 0)//插入入库表记录，插入库存表库记录
                    {
                        MessageBox.Show("入库成功！");
                        FrmInStoreManager_Load(sender, e);
                    }
                    else
                    {
                        MessageBox.Show("入库失败！请检查！");
                    }
                }



                
            }
        }


        //修改
        private void btnRevise_Click(object sender, EventArgs e)
        {
            if (cmbGoodsNum.Text.Length == 0 || cmbGoodsName.Text.Length == 0 || cmbStoreName.Text.Length == 0 || cmbSupplierName.Text.Length == 0 || cmbSpe.Text.Length == 0 || cmbUnits.Text.Length == 0 || cmbInStoreMonovalent.Text.Length == 0 || txtInStoreQuantity.Text.Trim().Length == 0 || txtTotal.Text.Trim().Length == 0 || txtHandler.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写完整！");
            }
            else
            {
                InStore inStore = new InStore
                {
                    InStoreID= dgvInStoreInfo[0,dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(),
                    GoodsID = cmbGoodsNum.Text,
                    StoreID = Convert.ToInt32(cmbStoreName.SelectedValue),
                    SupplierID = Convert.ToInt32(cmbSupplierName.SelectedValue),
                    InStoreMonovalent = Convert.ToDouble(cmbInStoreMonovalent.Text.Trim()),
                    InStoreQuantity = Convert.ToInt32(txtInStoreQuantity.Text.Trim()),
                    InStoreTotal = Convert.ToDouble(txtTotal.Text.Trim()),
                    InStoreTime = DateTime.Now.ToString("yyyy年MM月dd日HH时mm分"),
                    Handler = txtHandler.Text.Trim(),
                    Remarks = txtRemarks.Text.Trim()
                };

                if (inStoreManager.ReviseInStoreInfo(inStore) > 0)
                {
                    MessageBox.Show("修改成功！");
                    FrmInStoreManager_Load(sender, e);
                }
                else
                {
                    MessageBox.Show("修改失败！请检查！");
                }
            }
        }


        //删除
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvInStoreInfo.CurrentCell != null && dgvInStoreInfo.CurrentCell.RowIndex != -1)
            {
                InStore inStore = new InStore
                {
                    InStoreID = dgvInStoreInfo[0, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString()

                };

                if (inStoreManager.DeleteInStoreInfo(inStore) > 0)
                {
                    MessageBox.Show("删除成功！");
                    FrmInStoreManager_Load(sender, e);
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            else
            {
                MessageBox.Show("请在列表中选择要删除的记录！", "提示");
            }
        }

        //选择货物编号
        private void cmbGoodsNum_SelectionChangeCommitted(object sender, EventArgs e)
        {
            List<GoodsFiles> list = goodsFilesManager.GetListOnSelectGoodsNum(cmbGoodsNum.Text);
            
            //Console.WriteLine(list[0].GoodsName);
            cmbGoodsName.Text = list[0].GoodsName;  //货物名称
            cmbSpe.Text = list[0].Spec;   //规格
            cmbUnits.Text = list[0].Units;  //计量单位
            cmbInStoreMonovalent.Text = Convert.ToString(list[0].Monovalent);  //单价
        }

        //计算总金额（单价改变）
        private void cmbInStoreMonovalent_TextChanged(object sender, EventArgs e)
        {
            if (txtInStoreQuantity.Text.Trim().Length!=0 && NumCheck(cmbInStoreMonovalent.Text) && NumCheck(txtInStoreQuantity.Text))
            {
                txtTotal.Text = Convert.ToString(Convert.ToDouble(cmbInStoreMonovalent.Text) * Convert.ToDouble(txtInStoreQuantity.Text));
            }
        }
        //计算总金额（数量改变）
        private void txtInStoreQuantity_TextChanged(object sender, EventArgs e)
        {
            if (cmbInStoreMonovalent.Text.Trim().Length != 0 && NumCheck(cmbInStoreMonovalent.Text) && NumCheck(txtInStoreQuantity.Text))
            {
                txtTotal.Text = Convert.ToString(Convert.ToDouble(cmbInStoreMonovalent.Text) * Convert.ToDouble(txtInStoreQuantity.Text));
            }
        }
        //数字验证
        public bool NumCheck(string num)
        {
            string pattern = @"^\d+|\d+\.\d+";

            return Regex.IsMatch(num, pattern);
        }
        //右键添加打印
        private void 添加到待打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string printNote = string.Format("{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}#{8}#{9}#{10}", dgvInStoreInfo[0,dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(),dgvInStoreInfo[1,dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[2, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[4, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[6, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[7, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[8, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[9, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[10, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[11, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvInStoreInfo[13, dgvInStoreInfo.CurrentCell.RowIndex].Value.ToString());
            if (printList.Contains(printNote))  //待打印记录已存在
            {
                return;
            }
            else
            {
                if (printList.Count >= 10)
                {
                    MessageBox.Show("一次只能添加打印10条记录！默认A4纸，太多放不下！");
                    return;
                }
                printList.Add(printNote);
                btnPrint.Text = "打印 "+printList.Count+"条";

            }
        }
        //弹出添加打印右键菜单
        private void dgvInStoreInfo_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                cmsAddPrint.Show(MousePosition.X, MousePosition.Y);
            }
        }
        //打印按钮单击
        private void btnPrint_Click(object sender, EventArgs e)
        {
            //删除存在的入库单
            DeleDOC();
            //写入表格数据
            if (printList.Count==0)
            {
                MessageBox.Show("请在列表中右键添加待打印的入库记录！");
            }
            else
            {
                #region 创建待打印word
                //创建一个文档对象
                Document doc = new Document();
                //添加一个section
                Section section = doc.AddSection();

                //纸张横向
                Section sec = doc.Sections[0];
                sec.PageSetup.Orientation = PageOrientation.Landscape;

                //添加标题
                Paragraph inStoreTitle = section.AddParagraph();
                inStoreTitle.AppendText("入库单");
                //设置标题格式
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Black;
                style1.CharacterFormat.FontName = "方正小标宋简体";
                style1.CharacterFormat.FontSize = 24f;
                doc.Styles.Add(style1);
                inStoreTitle.ApplyStyle("titleStyle");
                //标题居中
                inStoreTitle.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                //添加单号
                Paragraph pStrat = section.AddParagraph();
                pStrat.AppendText("单号：rkd" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                //设置单号格式
                ParagraphStyle style12 = new ParagraphStyle(doc);
                style12.Name = "oddNumStyle";
                style12.CharacterFormat.Bold = false;
                style12.CharacterFormat.TextColor = Color.Black;
                style12.CharacterFormat.FontName = "宋体";
                style12.CharacterFormat.FontSize = 12f;
                doc.Styles.Add(style12);
                pStrat.ApplyStyle("oddNumStyle");

                //添加表格
                //Section section = doc.AddSection(); //添加section
                Table table = section.AddTable(true);
                //指定表格的行数和列数（11行，11列）
                table.ResetCells(11, 11);

                //标题行数组
                string[] tabTitle = { "入库编号", "货物编号", "货物名称", "仓库名称", "供货商", "规格", "计量单位", "单价", "入库数量", "入库总额", "经手人" };
                //添加表格标题行
                for (int i = 0; i < 1; i++)
                {
                    for (int j = 0; j < 11; j++)
                    {
                        TextRange range = table[i, j].AddParagraph().AppendText(tabTitle[j]);
                        range.CharacterFormat.FontName = "黑体";
                        range.CharacterFormat.FontSize = 12;
                        range.CharacterFormat.TextColor = Color.Black;
                        range.CharacterFormat.Bold = false;
                        table[i, j].Paragraphs[0].Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;  //水平居中
                        table[i, j].CellFormat.VerticalAlignment = VerticalAlignment.Middle;    //垂直居中
                    }
                }

                //遍历打印列表并插入表格数据
                for(int i = 0; i < printList.Count; i++)
                {
                    string[] arr = printList[i].Split('#');
                    for (int j = 0; j < 11; j++)
                    {
                        TextRange range = table[i+1, j].AddParagraph().AppendText(arr[j]);
                        range.CharacterFormat.FontName = "宋体";
                        range.CharacterFormat.FontSize = 10;
                        range.CharacterFormat.TextColor = Color.Black;
                        range.CharacterFormat.Bold = false;
                        table[i+1, j].CellFormat.VerticalAlignment = VerticalAlignment.Middle;    //垂直居中
                    }
                }
                //添加签字栏
                Paragraph pEnd = section.AddParagraph();
                pEnd.AppendText("制单人：              审核人：              日期：    年  月  日");
                //设置签字栏格式
                ParagraphStyle style13 = new ParagraphStyle(doc);
                style13.Name = "endLineStyle";
                style13.CharacterFormat.Bold = false;
                style13.CharacterFormat.TextColor = Color.Black;
                style13.CharacterFormat.FontName = "宋体";
                style13.CharacterFormat.FontSize = 12f;
                doc.Styles.Add(style13);
                pEnd.ApplyStyle("endLineStyle");

                //保存文档
                doc.SaveToFile("./inStoreDoc.docx", FileFormat.Docx2013);
                #endregion

                System.Threading.Thread.Sleep(1000);

                #region 开始打印
                //初始化PrintDialog实例
                PrintDialog dialog = new PrintDialog();

                //设置打印对话框属性
                dialog.AllowPrintToFile = true;
                dialog.AllowCurrentPage = true;
                dialog.AllowSomePages = true;

                //设置文档打印对话框
                doc.PrintDialog = dialog;

                //显示打印对话框并点击确定执行打印
                System.Drawing.Printing.PrintDocument printDoc = doc.PrintDocument;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    printDoc.Print();
                }
                DeleDOC();
                #endregion
            }

        }

        /// <summary>
        /// 删除insStoreDOC.docx文件
        /// </summary>
        public void DeleDOC()
        {
            if (System.IO.File.Exists("./inStoreDoc.docx"))
            {
                System.IO.File.Delete("./inStoreDoc.docx");
            }
        }
        //清空待打印列表
        private void 清空待打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            printList.Clear();
            btnPrint.Text = "打印";
        }
        //弹出清空待打印菜单
        private void btnPrint_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                cmsClearPrintList.Show(MousePosition.X, MousePosition.Y);
            }
        }
    }
}
